package club.mzwh.security.action;

import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import club.mzwh.common.util.HttpGetUtil;

@Controller
public class SSOAction {

	@RequestMapping(value="/front_login")
	public ModelAndView front_ready(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView result=new ModelAndView("/front/front_login");
		result.addObject("qqAuthUrl","https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=***&redirect_uri=***&state=test");
		result.addObject("baiduAuthUrl", "http://openapi.baidu.com/oauth/2.0/authorize?response_type=code&client_id=***&redirect_uri=***");
		result.addObject("xinlangAuthUrl", "https://api.weibo.com/oauth2/authorize?client_id=***&redirect_uri=***");
		result.addObject("weixinAuthUrl", "https://open.weixin.qq.com/connect/qrconnect?appid=***&redirect_uri=***&response_type=code&scope=snsapi_login");
		result.addObject("renrenAuthUrl", "https://graph.renren.com/oauth/authorize?client_id=***&redirect_uri=***&response_type=code");
		return result;
	}
	
	@ResponseBody
	@RequestMapping(value = "/sso/test", method = RequestMethod.POST)
	public String test(HttpServletRequest request, HttpServletResponse response) {
		try {
			Enumeration<String> headerNames = request.getHeaderNames();
			Map<String, String> headers = new HashMap<>(); 
	        while (headerNames.hasMoreElements()) {
	            String name = headerNames.nextElement();
	            //根据名称获取请求头的值
	            String value = request.getHeader(name);
	            System.out.println(name+"---"+value);
	            headers.put(name, value);
	        }
			//String tokenurl = "http://localhost:8080/oauth/authorize?client_id=TestSSO&redirect_uri=http://localhost:8088/sso/auth/nw&response_type=code";
			String tokenurl = "http://localhost:8080/check/token/test";
			String ret = HttpGetUtil.get1(tokenurl, null, headers);
			System.out.println("ret=="+ret);
			return ret;
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}
	
	@RequestMapping(value="/js/3login")
	public ModelAndView o3login(HttpServletRequest request, HttpServletResponse response) throws IOException {
		ModelAndView result=null;
		String code=request.getParameter("code");//客户端传回来的授权码
		String atokenUrl="https://openapi.baidu.com/oauth/2.0/token?grant_type=authorization_code&code="+code+"&client_id=***&client_secret=***&redirect_uri=***";
		String ret =HttpGetUtil.httpGet(atokenUrl);//返回带token的json字符串
//		com.alibaba.fastjson.JSONObject obj = JSON.parseObject(ret);
//		String access_token=(String) obj.get("access_token");//取出token
//		String apiUrl="https://openapi.baidu.com/rest/2.0/passport/users/getInfo?access_token="+access_token;
//		String uinfoma = HttpGetUtil.httpGet(apiUrl);//返回的用户信息json字符串
//		if(uinfoma!=null){//授权成功
//	
//		if(request.getSession().getAttribute("user")==null){//说明是登录页面来的
//	
//		com.alibaba.fastjson.JSONObject oobj = JSON.parseObject(uinfoma);
//		String birthday=(String) oobj.get("birthday");
//		String portrait=(String) oobj.get("portrait");
//		String userid=(String) oobj.get("userid");
//		String username=(String) oobj.get("username");
//		String thirdId="baidu_"+userid;//第三方平台的id
//		UserInfo userbyRelationId = userInfoService.getByRelationId(thirdId);//判断是账号是否关联过本地账号
//		if(userbyRelationId==null){//没有关联则注册一个本地账号
//		UserInfo user=null;
//		user = userInfoService.getByThirdId(thirdId);
//		String flag=null;//照片名
//		if(user !=null){
//	
//		flag=user.getUserId()+".jpg";
//		user.setNickname(username);
//		userInfoService.user_update(user);// 更新姓名（昵称）
//		user =userInfoService.getUserInfo(user.getUserId());
//		request.getSession().setAttribute("user", user);
//		}else{
//	
//		UserInfo uinfo=new UserInfo();
//		uinfo.setBirthday(birthday);//生日
//		uinfo.setNickname(username);//昵称
//		Date date=new Date();
//		String time=DateUtil.getDateTimeString(date);
//		uinfo.setCreateTime(time);//创建日期
//		uinfo.setStatus(0);//默认初始值为0
//		uinfo.setThirdId(thirdId);
//		int userId=userInfoService.insert(uinfo);
//		if(userId>=0){
//		StringBuffer sb=new StringBuffer();
//		sb.append(userId);
//		String entwoCodeFileName=sb.toString()+".jpg";//二维码图片文件名
//		String path=request.getContextPath();
//		String realpath=request.getSession().getServletContext().getRealPath("/");
//		String an=URLEncoder.encode("&");//&转码
//		StringBuffer rootUrl=request.getRequestURL();
//		String tempContextUrl = rootUrl.delete(rootUrl.length() - request.getRequestURI().length(), rootUrl.length()).toString();
//		String url=tempContextUrl+path+"/userInfo/areward_jump.htm?userId="+userId+"¶m=1";//二维码
//		String durl=final_param.CNURL+tempContextUrl+path+"/userInfo/areward_jump.htm?userId="+userId+an+"param=0";//短链接
//		String returl=url;//二维码
//		String retdurl=EntwocodeUtil.geturl(durl);//短链接
//		String twocodepath=realpath+File.separator+"upload"+File.separator+"twocode"+File.separator+entwoCodeFileName;//二维码存放的路径
//		EntwocodeUtil.encodePR(returl,150,150,twocodepath);//生成二维码
//		uinfo.setLink(retdurl);
//		uinfo.setQrCode("/upload/twocode/"+entwoCodeFileName);
//		uinfo.setUserId(userId);
//		userInfoService.user_update(uinfo);
//		uinfo =userInfoService.getUserInfo(uinfo.getUserId());
//		request.getSession().setAttribute("user", uinfo);
//		flag=userId+".jpg";
//	
//		}
//		// 写头像文件
//		String portraitUrl="http://tb.himg.baidu.com/sys/portrait/item/"+portrait;
//		byte[] portraitData = BaiduUtil.downloadPortrait(portraitUrl);
//		String basePath = request.getSession().getServletContext().getRealPath("/");
//		BaiduUtil.savePortrait(basePath+File.separator+"portrait"+File.separator+flag, portraitData);//图片写入文件夹下，图片名与用户id对应
//	
//		}
//		result= new ModelAndView("redirect:/userInfo/front_main.htm");//进入用户主页
//		}else{//有关联就取出信息
//	
//		request.getSession().setAttribute("user", userbyRelationId);
//		result= new ModelAndView("redirect:/userInfo/front_main.htm");//进入用户主页
//	
//		}
//		}else{//从绑定页面来的
//	
//		UserInfo user=(UserInfo) request.getSession().getAttribute("user");
//		com.alibaba.fastjson.JSONObject oobj = JSON.parseObject(uinfoma);
//		String userid=(String) oobj.get("userid");
//		String relationId="baidu_"+userid;//绑定的百度平台的id
//		UserInfo byrelationId = userInfoService.getByThirdId(relationId);//查询在绑定该账号前，该帐号是否已被注册过
//		if(byrelationId!=null){
//	
//		String authErrorName=byrelationId.getNickname();
//		//String thirdId=byrelationId.getThirdId();
//		request.getSession().setAttribute("authErrorName", authErrorName);
//		result=new ModelAndView("redirect:/userInfo/auth_error.htm");//提示该账号已经绑定过了
//	
//		}else{
//	
//		user.setRelationId(relationId);
//		userInfoService.user_update(user);
//		user=userInfoService.getUserInfo(user.getUserId());
//		request.getSession().setAttribute("user", user);
//		request.getSession().setAttribute("relationState", 1);//提示已经绑定成功
//		result=new ModelAndView("redirect:/userInfo/front_main_3.htm");
//		}
//	
//		}
//	
//		}
		return result;
	}
	
}
